package com.comba.javafxdemo;

import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.controlsfx.dialog.Dialogs;

import com.comba.javafxdemo.controller.PersonOverviewController;
import com.comba.javafxdemo.controller.RootLayoutController;
import com.comba.javafxdemo.model.Person;
import com.comba.javafxdemo.model.PersonListWrapper;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MainApp extends Application {
	private ObservableList<Person> personData = FXCollections.observableArrayList();

	private Stage primaryStage;
	private BorderPane rootLayout;

	public MainApp() {
		// Add some sample data
		personData.add(new Person("Hans", "Muster"));
		personData.add(new Person("Ruth", "Mueller"));
		personData.add(new Person("Heinz", "Kurz"));
		personData.add(new Person("Cornelia", "Meier"));
		personData.add(new Person("Werner", "Meyer"));
		personData.add(new Person("Lydia", "Kunz"));
		personData.add(new Person("Anna", "Best"));
		personData.add(new Person("Stefan", "Meier"));
		personData.add(new Person("Martin", "Mueller"));
	}

	public ObservableList<Person> getPersonData() {
		return personData;
	}

	@Override
	public void start(Stage primaryStage) {
		this.primaryStage = primaryStage;
		this.primaryStage.setTitle("Address App");
		this.primaryStage.getIcons().add(new Image(this.getClass().getResourceAsStream("/images/address_book_32.png")));

		initRootLayout();
		showPersonOverview();
	}

	private void initRootLayout() {
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("/com/comba/javafxdemo/view/RootLayout.fxml"));
		try {
			this.rootLayout = loader.load();
			Scene scene = new Scene(rootLayout);
			this.primaryStage.setScene(scene);
			this.primaryStage.show();

			RootLayoutController controller = loader.getController();
			controller.setMainApp(this);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		File file = this.getPersonFilePath();
		if(file!=null) {
			this.loadPersonDataFromFile(file);
		}
	}

	private void showPersonOverview() {
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("/com/comba/javafxdemo/view/PersonOverview.fxml"));
		try {
			AnchorPane personOverview = loader.load();
			this.rootLayout.setCenter(personOverview);

			// 要想获取Controller，必须在PersonOverview.fxml的根元素在配置fx:controller
			PersonOverviewController controller = loader.getController();
			controller.setMainApp(this);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Stage getPrimaryStage() {
		return primaryStage;
	}

	public File getPersonFilePath() {
		Preferences preferences = Preferences.userNodeForPackage(MainApp.class);
		String filepath = preferences.get("filepath", null);
		return filepath==null ? null : new File(filepath);
	}

	public void setPersonFilePath(File file) {
		Preferences preferences = Preferences.userNodeForPackage(MainApp.class);
		if(file != null && file.exists() && file.isFile()) {
			preferences.put("filepath", file.getAbsolutePath());
			this.primaryStage.setTitle("AddressApp - " + file.getPath());
		} else {
			preferences.remove("filepath");
			this.primaryStage.setTitle("AddressApp");
		}
	}

	public void loadPersonDataFromFile(File file) {
		try {
			JAXBContext context = JAXBContext.newInstance(PersonListWrapper.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			PersonListWrapper wrapper = (PersonListWrapper) unmarshaller.unmarshal(file);
			this.personData.clear();
			this.personData.addAll(wrapper.getPersons());

			this.setPersonFilePath(file);
		} catch(Exception e) {
			Dialogs.create().title("Error")
            	.masthead("Could not load data from file:\n" + file.getPath())
            	.showException(e);
		}
	}

	public void savePersonDataToFile(File file) {
		try {
			JAXBContext context = JAXBContext.newInstance(PersonListWrapper.class);
			Marshaller marshaller = context.createMarshaller();
			PersonListWrapper wrapper = new PersonListWrapper();
			wrapper.setPersons(this.personData);
			marshaller.marshal(wrapper, file);

			this.setPersonFilePath(file);
		} catch(Exception e) {
			Dialogs.create().title("Error")
            	.masthead("Could not save data to file:\n" + file.getPath())
            	.showException(e);
		}
	}




	public static void main(String[] args) {
		launch(args);
	}
}
